package vip.xiaomoli.idempotent.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import vip.xiaomoli.idempotent.component.DBCleaner;

import javax.sql.DataSource;

@Configuration
public class IdempotentAutoConfiguration {

    @Value("classpath:sql/IdempotentInit.sql")
    private Resource idempotentInitSql;

    @Bean
    @javax.annotation.Resource
    public DataSourceInitializer dataSourceInitializer(DataSource dataSource) {
        DataSourceInitializer initializer = new DataSourceInitializer();
        initializer.setDataSource(dataSource);
        ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
        populator.addScripts(idempotentInitSql);
        initializer.setDatabasePopulator(populator);
        new DBCleaner(dataSource);
        return initializer;
    }

}
